package hk.m4s.lr.repair.test.ui.user;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.bumptech.glide.Glide;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.takephoto.CustomHelper;
import framework.common.widgets.dialogs.UeDialog;
import framework.common.zanetwork.core.ResponseCallback;
import framework.common.zanetwork.core.UploadCallback;
import framework.common.zanetwork.core.UploadHelper;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.ImageModle;
import hk.m4s.lr.repair.test.model.MyWaiteOrderModel;
import hk.m4s.lr.repair.test.model.TableModel;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.ui.adapter.EnAdaper;
import hk.m4s.lr.repair.test.ui.adapter.GridViewAdapter;
import hk.m4s.lr.repair.test.utils.CustomerAlertDialog;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.InnerGridView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/5/4.
 *  我要评价
 */

public class OrderEnActivity extends UeBaseActivity implements View.OnClickListener,AdapterView.OnItemClickListener {
    private  TextView fanwei_tips,home_send_order;
    private MyWaiteOrderModel myOrderModel;
    private List<TableModel> list=new ArrayList<>();
    private Context context;
    TextView order_shop_name;
    ImageView order_shop_img;
    private EditText add_en;
    private InnerGridView enYin;
    private RatingBar rc_rate;
    float rant=5;
    private EnAdaper adaper;
    private String key="";
    private String content="";
    private int state=1;
    // 图片 九宫格
    private InnerGridView gv;
    // 图片 九宫格适配器
    private GridViewAdapter gvAdapter;

    // 用于保存图片资源文件
    private List<Bitmap> lists = new ArrayList<Bitmap>();
    private ArrayList<TImage> imgList;
    // 用于保存图片路径
    private List<ImageModle> imgs = new ArrayList<ImageModle>();
    // 拍照
    public static final int IMAGE_CAPTURE = 1;
    // 从相册选择
    public static final int IMAGE_SELECT = 2;
    // 照片缩小比例
    private static final int SCALE = 5;
    private String img,goodsName,goodsId,orderId,orderSize,ids;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_en_order);
        hiddenFooter();
        showGoBackBtn();
        context=this;
        setTitleText("我要评价");

        findbaseView();
    }
    public void findbaseView(){
        rc_rate=(RatingBar) findViewById(R.id.rc_rate);
        home_send_order=(TextView) findViewById(R.id.home_send_order);
        order_shop_name = (TextView)findViewById(R.id.order_shop_name);
        order_shop_img = (ImageView)findViewById(R.id.order_shop_img);
        gv= (InnerGridView) findViewById(R.id.noScrollgridview);
        fanwei_tips= (TextView)findViewById(R.id.fanwei_tips);
        add_en= (EditText) findViewById(R.id.add_en);
        enYin=(InnerGridView) findViewById(R.id.enYin);
        img=getIntent().getStringExtra("img");
        goodsName=getIntent().getStringExtra("goodsName");
        ids=getIntent().getStringExtra("ids");
        goodsId=getIntent().getStringExtra("goodsId");
        orderId=getIntent().getStringExtra("orderId");
        orderSize=getIntent().getStringExtra("orderSize");
        adaper=new EnAdaper(context,list);
        enYin.setAdapter(adaper);
        enYin.setOnItemClickListener(clickItem);
        fanwei_tips.setOnClickListener(this);
        home_send_order.setOnClickListener(this);
        rc_rate.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                rant=rating;
            }
        });
       // order_shop_name.setText(goodsName);
//        try {
//            Glide.with(context).load(img).asBitmap().placeholder(R.mipmap.device_list_no_img).error(R.mipmap.device_list_no_img).into(order_shop_img);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        gvAdapter = new GridViewAdapter(this, imgs,"2");
        gv.setOnItemClickListener(this);
        gv.setAdapter(gvAdapter);
        gvAdapter.setList(imgs);
        //getTabs();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fanwei_tips:
                 if(state==1){
                     state=0;
                     showImg(R.mipmap.checked_hover,fanwei_tips);
                 }else{
                     state=1;
                     showImg(R.mipmap.check,fanwei_tips);
                 }
                break;
            case R.id.home_send_order:
                if(add_en.getText().toString().equals("")){
                    ToastUtil.toast(context,"请填写评价内容");
                    return;
                }
                content=add_en.getText().toString();
                //putEn();
                break;
        }
    }
//    public void putEn() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("user", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.evaluate_token,""));
//        parmas.put("object",goodsId);
//        parmas.put("userLogo", SharedPreferencesUtils.getSharedPreferences(Constant.face, ""));
//        parmas.put("anonymous",state);
//        try {
//            JSONObject obj = new JSONObject();
//            obj.put("order_id", orderId);
//            obj.put("id", ids);
//            parmas.put("extObject", obj);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if(state==1){
//            parmas.put("anonymousName", "匿名评论");
//        }else {
//            if(!(SharedPreferencesUtils.getSharedPreferences(Constant.nickName, "")==null|| SharedPreferencesUtils.getSharedPreferences(Constant.nickName, "").equals(""))){
//                parmas.put("anonymousName", SharedPreferencesUtils.getSharedPreferences(Constant.nickName, ""));
//            }else {
//                parmas.put("anonymousName", "未命名");
//            }
//        }
//        if(key.equals("")) {
//            parmas.put("tabsFlag","-1" );
//        }else{
//            parmas.put("tabsFlag","1");
//            if(adaper.list.size()>0) {
//                try {
//                    JSONArray array=new JSONArray();
//                    for (int i = 0; i < adaper.list.size(); i++) {
//                        TableModel model = adaper.list.get(i);
//                        if(model.getSelect().equals("2")) {
//                            JSONObject obj = new JSONObject();
//                            obj.put("key", model.getKeycode());
//                            array.put(obj);
//                        }
//                    }
//                    parmas.put("tabs",array.toString());
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }
//        parmas.put("grade",rant);
//        parmas.put("content",content);
//        parmas.put("remarkText",orderSize);
//        if(imgs.size()>0) {
//            try {
//                JSONArray array=new JSONArray();
//                for (int i = 0; i < imgs.size(); i++) {
//                    ImageModle model =imgs.get(i);
//                        JSONObject obj = new JSONObject();
//                        obj.put("url", model.getUrl());
//                        array.put(obj);
//                }
//                parmas.put("pics",array.toString());
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//        AccountSerive.putEn(context, parmas, new ResponseCallback<enValueModel>() {
//            @Override
//            public void onSuccess(enValueModel userinfoModel) {
//                finish();
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//
//    }
//    public void getTabs() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//       parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.evaluate_token,""));
//        AccountSerive.getTabs(context, parmas, new ResponseCallback<TableModel>() {
//            @Override
//            public void onSuccess(TableModel model) {
//                if(model.getList()!=null){
//                    list.clear();
//                    list.addAll(model.getList());
//                    adaper.notifyDataSetChanged();
//                }
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//
//    }
    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
//            TableModel model=list.get(arg2);
//            if(model.getSelect().equals("1")){
//                model.setSelect("2");
//            }else{
//                model.setSelect("1");
//            }
//            list.set(arg2,model);
//            adaper.notifyDataSetChanged();
//            key=model.getKeycode();

        }

    };
    public void showImg(int resId, TextView myTextview) {
        Drawable drawable = context.getResources().getDrawable(resId);
/// 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        myTextview.setCompoundDrawables(drawable, null, null, null);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position,
                            long id) {
        if (position == getDataSize()) {// 点击“+”号位置添加图片
            if(imgs.size()==9){
                  ToastUtil.toast(context,"最大允许9张");
            }else {
                CustomerAlertDialog.showAlertDialog(OrderEnActivity.this, false, "提示", new String[]{"拍照", "从图库选择", "取消"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which + 1) {
                                    case 1:// 拍照
                                        CustomHelper.onClick(getTakePhoto(), 0);
                                        dialog.dismiss();
                                        break;
                                    case 2:// 从图库选择
                                        int num = 9 - imgs.size();
                                        if (num > 0) {
                                            CustomHelper.onClick(getTakePhoto(), 1);
                                        }
                                        dialog.dismiss();
                                        break;
                                    case 3:// 取消
                                        dialog.dismiss();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        });
            }
        } else {// 点击图片删除
            CustomerAlertDialog.showAlertDialog(OrderEnActivity.this,"提示", "是否删除此图片？", "确定", "取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //lists.remove(position);
                    //FileUtils.delFile(list_path.get(position));
                    imgs.remove(position-1);
                    gvAdapter.setList(imgs);
                    dialog.dismiss();
                }
            }, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }
    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Message msg=new Message();
        msg.obj=result.getImages();
        handler.sendMessage(msg);


    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imgList = (ArrayList<TImage>) msg.obj;
            if(imgList!=null) {
                new UploadHelper().asyncPutObjectFromLocalFile(context, Constant.endpoint, imgList.get(0).getCompressPath(), new UploadCallback<Integer>() {
                    @Override
                    public void onRequestBefore() {
                        UeDialog.showprogressDialog(context,"","上传中...",false);
                    }

                    @Override
                    public void onFailure(PutObjectRequest response, String failureMsg, int code) {
                        UeDialog.hideProgress();
                    }

                    @Override
                    public void onSuccess(PutObjectRequest response, Integer o) {
                        UeDialog.hideProgress();
                        if (o == 200) {
                            String logo = "https://" + Constant.testBucket + ".oss-cn-beijing.aliyuncs.com" + "/" +response.getObjectKey();
                            ImageModle modle=new ImageModle();
                            modle.setUrl(logo);
                            imgs.add(modle);
                            if(imgs!=null){
                                gv.setAdapter(gvAdapter);
                                gvAdapter.setList(imgs);
                            }
                        }
                    }

                    @Override
                    public void onError(PutObjectRequest response, int errorCode, Exception e) {

                    }
                });
            }
        }
    };
    private int getDataSize() {
        return imgs.size() == 0 ? 0 : imgs.size();
    }


}
